<template>
  <div id="treeTable">
    <div style="margin-top: 15px;margin-bottom: 15px; width: 100%; ">
      <span style="font-size: 25px;fobnt-weight: bold;">设备管理</span>
      <!-- <a-button danger style="margin-left: 100px;">抓图</a-button> -->
    </div>
    <a-input-search v-model:value="searchValue" placeholder="请输入企业名" style="margin-bottom: 8px" />
    <a-tree
      :expanded-keys="expandedKeys"
      :auto-expand-parent="autoExpandParent"
      :tree-data="gData"
      @expand="onExpand"
      style="background-color: #f0f2f5; "
    >
      <template #title="{ title, key }">
        <span v-if="title.indexOf(searchValue) > -1">
          {{ title.substring(0, title.indexOf(searchValue)) }}
          <span style="color: #f50">{{ searchValue }}</span>
          {{ title.substring(title.indexOf(searchValue) + searchValue.length) }}
        </span>
        <span v-else>{{ title }}</span>
        <span v-if="isParentNode(key)">
          <PlusOutlined @click="addNode(key)" />
        </span>
        <span v-else>
          <!-- 添加点击事件处理函数 -->
          <VideoCameraOutlined @click="playVideo(key)" />
          <FormOutlined @click="editNode(key)" />
          <DeleteOutlined @click="deleteNode(key)" />
        </span>
      </template>
    </a-tree>
    <DeviceAddForm
      :open="deviceAddVisible" 
      :parentKey="currentParentKey"
      :parentName="currentParentName"
      :parentUnitCode="currentParentUnitCode"
      :editData="editData"
      @deviceAdded="handleDeviceAdded"
      @cancel="handleDeviceAddCancel"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, defineProps, defineExpose, toRaw } from 'vue';
import type { TreeProps } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { VideoCameraOutlined, FormOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { deviceInfoListData, deviceInfoSave, deviceInfoDelete, deviceInfoForm } from '/@/api/safealarm/deviceInfo';
import { unitEnterpriseDominantListData } from '/@/api/unitmanage/unitEnterpriseDominant';
import DeviceAddForm from './DeviceAddForm.vue';
import SafeVideo from './safevideo.vue';

const props = defineProps({
  safeVideoRef: {
    type: Object,
    default: null
  }
});
console.log(props);

const expandedKeys = ref<(string | number)[]>([]);
const searchValue = ref<string>('');
const autoExpandParent = ref<boolean>(true);
const gData = ref<TreeProps['treeData']>([]);
const dataList: TreeProps['treeData'] = [];
const deviceAddVisible = ref(false);
const currentParentKey = ref<string | number | null>(null);
const currentParentName = ref('');
const currentParentUnitCode = ref('');
const editData = ref(null);
const isVideoVisible = ref(true);
const safeVideoRef = props.safeVideoRef;
// 用于记录已经加载过子节点的节点 key
const loadedKeys = ref<(string | number)[]>([]);

const onExpand = async (keys: string[]) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;

  // 遍历展开的节点，检查是否需要加载子节点
  for (const key of keys) {
    const node = findNode(key, gData.value);
    if (node && node.children.length === 0 &&!node.isLeaf &&!loadedKeys.value.includes(key)) {
      try {
        let allChildNodes: any[] = [];
        let pageNo = 1;
        let hasMoreChild = true;
        while (hasMoreChild) {
          const childParams = { pageNo, pageSize: 20, enterpriseId: node.unitCode };
          const childResponse = await deviceInfoListData(childParams);
          allChildNodes = allChildNodes.concat(childResponse.list);
          hasMoreChild = childResponse.list.length === childParams.pageSize;
          pageNo++;
        }
        const childNodes = allChildNodes.filter(item => item.name).map(item => {
          // 假设 state 属性存在于响应数据中
          const state = item.state || ''; 
          return {
            key: item.id.toString(),
            // 将 state 值添加到 title 之前
            title: `${state} ${item.name}`, 
            isLeaf: true
          };
        });
        node.children = childNodes;
        // 标记该节点已加载子节点
        loadedKeys.value.push(key);
        // 使用深拷贝更新数据
        // gData.value = JSONParse(JSONStringify(toRaw(gData.value)));
      } catch (error) {
        // message.error('Failed to fetch child data');
      }
    }
  }
};

watch(searchValue, async (value) => {
  try {
    let allParentNodes: any[] = [];
    let pageNo = 1;
    let hasMoreParent = true;
    while (hasMoreParent) {
      const parentParams = { pageNo, pageSize: 20, name: value };
      const parentResponse = await unitEnterpriseDominantListData(parentParams);
      allParentNodes = allParentNodes.concat(parentResponse.list);
      hasMoreParent = parentResponse.list.length === parentParams.pageSize;
      pageNo++;
    }
    const parentNodes = allParentNodes.map(item => ({
      key: item.id.toString(),
      title: item.name,
      unitCode: item.unitCode,
      children: [],
      isLeaf: false
    }));

    gData.value = parentNodes;
    // 清空已加载列表
    loadedKeys.value = [];
    generateList(gData.value);
  } catch (error) {
    message.error('Failed to fetch data based on search value');
  }

  const expanded = dataList
    .map((item: TreeProps['treeData'][number]) => {
      if (item.title.indexOf(value) > -1) {
        return getParentKey(item.key, gData.value);
      }
      return null;
    })
    .filter((item, i, self) => item && self.indexOf(item) === i);
  expandedKeys.value = expanded;
  searchValue.value = value;
  autoExpandParent.value = true;
});

const isParentNode = (key: string | number) => {
  const node = findNode(key, gData.value);
  return node &&!node.isLeaf;
};

const addNode = (parentKey: string | number) => {
  const parentNode = findNode(parentKey, gData.value);
  if (parentNode) {
    currentParentKey.value = parentKey;
    currentParentName.value = parentNode.title;
    currentParentUnitCode.value = parentNode.unitCode;
    editData.value = null;
    deviceAddVisible.value = true;
    isVideoVisible.value = false;
  } else {
    message.warning('You cannot add more children to this node.');
  }
};

const deleteNode = async (key: string | number) => {
  try {
    const response = await deviceInfoDelete({ tid: key });
    if (response.result === "true") {
      const parentKey = getParentKey(key, gData.value);
      if (parentKey) {
        const parentNode = findNode(parentKey, gData.value);
        if (parentNode && parentNode.children) {
          parentNode.children = parentNode.children.filter(item => item.key !== key);
          // 使用深拷贝更新数据
          // gData.value = JSONParse(JSONStringify(toRaw(gData.value)));
        }
      } else {
        gData.value = gData.value.filter(item => item.key !== key);
      }
      // 从已加载列表中移除该节点
      loadedKeys.value = loadedKeys.value.filter(k => k!== key);
      message.success('节点删除成功');
    } else {
      message.error('节点删除失败');
    }
  } catch (error) {
    console.error('删除节点时出错:', error);
    message.error('删除节点时出错，请重试');
  }
};

const editNode = async (key: string | number) => {
  try {
    const response = await deviceInfoForm({ tid: key });
    if (response.deviceInfo) {
      const parentKey = getParentKey(key, gData.value);
      const parentNode = findNode(parentKey, gData.value);
      if (parentNode) {
        currentParentKey.value = parentKey;
        currentParentName.value = parentNode.title;
        currentParentUnitCode.value = parentNode.unitCode;
        editData.value = response.deviceInfo;
        deviceAddVisible.value = true;
        isVideoVisible.value = false;
      } else {
        console.error('Parent node not found');
        message.error('Failed to find parent node');
      }
    } else {
      console.error('Failed to get device info:', response);
      message.error('Failed to get device info');
    }
  } catch (error) {
    console.error('Error while getting device info:', error);
    message.error('Failed to get device info');
  }
};

const findNode = (
  key: string | number,
  tree: TreeProps['treeData'],
): TreeProps['treeData'][number] | undefined => {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.key === key) {
      return node;
    }
    if (node.children) {
      const found = findNode(key, node.children);
      if (found) {
        return found;
      }
    }
  }
  return undefined;
};

const getParentKey = (
  key: string | number,
  tree: TreeProps['treeData'],
): string | number | undefined => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

const generateList = (data: TreeProps['treeData']) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const key = node.key;
    dataList.push({ key, title: key });
    if (node.children) {
      generateList(node.children);
    }
  }
};

const handleDeviceAdded = async () => {
  try {
    let allParentNodes: any[] = [];
    let pageNo = 1;
    let hasMoreParent = true;
    while (hasMoreParent) {
      const parentParams = { pageNo, pageSize: 20 };
      const parentResponse = await unitEnterpriseDominantListData(parentParams);
      allParentNodes = allParentNodes.concat(parentResponse.list);
      hasMoreParent = parentResponse.list.length === parentParams.pageSize;
      pageNo++;
    }
    const parentNodes = allParentNodes.map(item => ({
      key: item.id.toString(),
      title: item.name,
      unitCode: item.unitCode,
      children: [],
      isLeaf: false
    }));

    gData.value = parentNodes;
    // 清空已加载列表
    loadedKeys.value = [];
    generateList(gData.value);
    deviceAddVisible.value = false;
    isVideoVisible.value = true;
  } catch (error) {
    message.error('Failed to fetch data');
  }
};

const handleDeviceAddCancel = () => {
  deviceAddVisible.value = false;
  isVideoVisible.value = true;
};

// 修改后的播放视频的方法
const playVideo = async (key: string | number) => {
  const node = findNode(key, gData.value);
  console.log('node:', node);
  if (node) {
    try {
      // 触发 deviceInfoListData 接口
      const response = await deviceInfoForm({ tid: key });;
      console.log('response:', response);
      const deviceInfo = response.deviceInfo;
      console.log('deviceInfo:', deviceInfo);
      console.log('props.safeVideoRef:', props.safeVideoRef);
      if (props.safeVideoRef) {
        props.safeVideoRef.play(deviceInfo);
        console.log('props.safeVideoRef', props.safeVideoRef.value);
      } else {
        console.error('SafeVideo 组件引用未准备好');
      }
    } catch (error) {
      console.error('Failed to fetch device info:', error);
      message.error('Failed to fetch device info');
    }
  }
};

onMounted(async () => {
  try {
    let allParentNodes: any[] = [];
    let pageNo = 1;
    let hasMoreParent = true;
    while (hasMoreParent) {
      const parentParams = { pageNo, pageSize: 20 };
      const parentResponse = await unitEnterpriseDominantListData(parentParams);
      allParentNodes = allParentNodes.concat(parentResponse.list);
      hasMoreParent = parentResponse.list.length === parentParams.pageSize;
      pageNo++;
    }
    const parentNodes = allParentNodes.map(item => ({
      key: item.id.toString(),
      title: item.name,
      unitCode: item.unitCode,
      children: [],
      isLeaf: false
    }));

    gData.value = parentNodes;
    // 初始化已加载列表
    loadedKeys.value = [];
    generateList(gData.value);
  } catch (error) {
    message.error('Failed to fetch data');
  }
});

defineExpose({
  isVideoVisible
})
</script>

<style scoped lang="less">
#treeTable {
  background-color: whitesmoke;
}
</style>